package com.wolfpire.workflow.assign;

import javax.annotation.Resource;

import org.jbpm.api.jpdl.DecisionHandler;
import org.jbpm.api.model.OpenExecution;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import com.wolfpire.workflow.dao.NodeDao;
import com.wolfpire.workflow.om.Node;

/**
 * 默认决策节点触发类
 * @author liushx 
 *
 */

@SuppressWarnings("serial")
public class DefaultDecisionHandlerImpl implements DecisionHandler{
	
	@Resource private NodeDao nodeDao;
	
	public String decide(OpenExecution execution) {
		//Integer days = (Integer) execution.getVariable("day");
		Long deploymentId  = (Long) execution.getVariable("deploymentId");
		
		//System.out.println("--------DefaultDecisionHandlerImpl-------");
		//String str = "day,&lt;,3,任务节点2|swed,==,3,任务节点3|day,&gt;,3,任务节点4";
		
		Node node = nodeDao.getNode(deploymentId, execution.getActivity().getName());
		
		return "to "+resolveExpr(node.getExprText(), execution);
	}

	public String resolveExpr(String exprText, OpenExecution execution){
		ExpressionParser parser= new SpelExpressionParser();  
		EvaluationContext context = new StandardEvaluationContext();  
		String res = "";
		String[] exprs = exprText.split("\\|");
		for (int i = 0; i < exprs.length; i++) {
			String[] strs = exprs[i].split("\\,");
			Integer val = (Integer) execution.getVariable(strs[0]);
			//context.setVariable(strs[0], val);
			String s = val+strs[1]+strs[2]+"?'"+strs[3]+"':''";
			String out =  parser.parseExpression(replaceHtml(s)).getValue(context, String.class);
			if("".equals(out)){
				continue;
			}
			res = out;
		}
		
		//System.out.println("res=="+res);

		return res;
	}
	

	protected String replaceHtml(String flowXml){
		
		return flowXml.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
	}

}
